const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    curNum:number = 0;
    second:number = 0;
    gameOverFlag:number = 0;
    @property(cc.Label)
    timeLabel:cc.Label = null;
    @property(cc.Label)
    curNumber:cc.Label = null;
    @property(cc.Node)
    gameOverNode:cc.Node = null;

    start () {
        this.initScene()
    }

    // update (dt) {}
    initScene(){
        this.curNum = 1
        this.second = 0
        this.gameOverFlag = 1
        this.curNumber.string = "当前数字:1";
        this.timeLabel.string = "时间:0";
        this.scheduleOnce(function() {
            // 这里的 this 指向 component
            this.recordTime()
        }, 1);
        let nodeWidth = (this.node.width-12)/7
        let startX = -this.node.width/2+nodeWidth/2
        let startY = 300
        let numArr = []
        function randomsort(a, b) {
            return Math.random()>.5 ? -1 : 1;
            //用Math.random()函数生成0~1之间的随机数与0.5比较，返回-1或1
        }
        for (let k=1;k<=49;k++){
            numArr.push(k) 
        }
        numArr.sort(randomsort);
        for(let i=1;i<=7;i++){
            for(let j=1;j<=7;j++){
                cc.loader.loadRes("NumberGrid",cc.Prefab, (err, prefab)=>{
                    let node = cc.instantiate(prefab);
                    cc.log(i,j);
                    node.width = nodeWidth;
                    node.height = nodeWidth;
                    node.parent = this.node;
                    let num = numArr.pop();
                    node.getComponent("NumberGrid").setContent(nodeWidth,num)
                    node.x =startX + (i-1)*(nodeWidth+1);
                    node.y = startY -(j-1)*(nodeWidth+1);
                    cc.log(node.x,node.y,nodeWidth);
                })
            }
        }
    }

    solveProduce(num,node:cc.Node){
        if (this.gameOverFlag==1){
            if (num==this.curNum){
                this.curNum += 1
                this.curNumber.string = "当前数字："+this.curNum;
                node.destroy();
                if(this.curNum==5){
                    this.gameOver();
                }
            }
        }
    }

    recordTime(){
        if (this.gameOverFlag==1){
            this.scheduleOnce(function() {
                // 这里的 this 指向 component
                this.second +=1;
                this.timeLabel.string = "时间："+this.second;
                this.recordTime()
            }, 1);
        }
    }

    gameOver(){
        this.gameOverFlag = 0;
        this.gameOverNode.x = 0;
        this.gameOverNode.zIndex = 1000;
    }

    restartGame(){
        this.gameOverNode.x = 1000;
        this.initScene();
    }
}
